#!/usr/bin/env python3
"""
Flask-Migrate数据库迁移脚本
"""

import os
import sys
from flask import Flask
from flask_migrate import Migrate, init, migrate, upgrade, downgrade, history
from tools.db import create_database, init_db
from models.users import *

def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 数据库配置
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:12345@localhost:3306/management_system?charset=utf8mb4'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化数据库
    db = init_db(app, use_mysql=True)
    
    return app

def init_migration():
    """初始化迁移文件夹"""
    print("📁 初始化迁移文件夹...")
    try:
        init()
        print("✅ 迁移文件夹初始化成功")
        return True
    except Exception as e:
        print(f"❌ 初始化失败: {str(e)}")
        return False

def create_migration(message="初始化数据库表"):
    """创建迁移脚本"""
    print(f"📝 创建迁移脚本: {message}")
    try:
        migrate(message=message)
        print("✅ 迁移脚本创建成功")
        return True
    except Exception as e:
        print(f"❌ 创建迁移脚本失败: {str(e)}")
        return False

def upgrade_database():
    """执行数据库升级"""
    print("⬆️ 执行数据库升级...")
    try:
        upgrade()
        print("✅ 数据库升级成功")
        return True
    except Exception as e:
        print(f"❌ 数据库升级失败: {str(e)}")
        return False

def downgrade_database():
    """回滚数据库"""
    print("⬇️ 回滚数据库...")
    try:
        downgrade()
        print("✅ 数据库回滚成功")
        return True
    except Exception as e:
        print(f"❌ 数据库回滚失败: {str(e)}")
        return False

def show_history():
    """显示迁移历史"""
    print("📊 迁移历史:")
    try:
        history()
        return True
    except Exception as e:
        print(f"❌ 显示历史失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("🗄️ Flask-Migrate数据库迁移工具")
    print("=" * 50)
    
    if len(sys.argv) < 2:
        print("用法:")
        print("  python migrate_db.py init          # 初始化迁移文件夹")
        print("  python migrate_db.py migrate        # 创建迁移脚本")
        print("  python migrate_db.py upgrade        # 执行数据库升级")
        print("  python migrate_db.py downgrade      # 回滚数据库")
        print("  python migrate_db.py history        # 显示迁移历史")
        return
    
    command = sys.argv[1]
    
    if command == "init":
        # 先创建数据库
        create_database()
        init_migration()
    elif command == "migrate":
        message = sys.argv[2] if len(sys.argv) > 2 else "数据库迁移"
        create_migration(message)
    elif command == "upgrade":
        upgrade_database()
    elif command == "downgrade":
        downgrade_database()
    elif command == "history":
        show_history()
    else:
        print(f"❌ 未知命令: {command}")

if __name__ == '__main__':
    main()
